package com.je.core.interceptor;

import cn.hutool.core.io.resource.ResourceUtil;
import com.je.cache.redis.RedisCache;
import com.je.core.util.StringUtil;
import org.hibernate.EmptyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Properties;


public class KingHiberInterceptor extends EmptyInterceptor {
    @Autowired
    private RedisCache redisCache;

    @Override
    public String onPrepareStatement(String sql) {
        String isK8r6 = redisCache.get("K8r6After")+"";
        if("null".equals(isK8r6) || StringUtil.isEmpty(isK8r6)){
            try {
                Properties env = new Properties();
                env.load(ResourceUtil.getStream("jdbc.properties"));
                String url = env.getProperty("jdbc.url");
                if(url.replaceAll(" ","").contains("K8r6After=true")){
                    isK8r6 = "true";
                    redisCache.put("K8r6After","true");
                }else{
                    isK8r6 = "false";
                    redisCache.put("K8r6After","false");
                }
            }catch (Exception e){
            }
        }
        if("false".equals(isK8r6)){
            return super.onPrepareStatement(sql);
        }
        String newSql = "";
        if(sql.contains("UPDATE") || sql.contains("update")){
            newSql = sql;
        }else{
            newSql = formatSql(sql);
        }
        return super.onPrepareStatement(newSql);
    }

    public String formatSql(String sql){
        return sql
                .replaceAll(" like "," ilike ")
                .replaceAll(" LIKE "," ILIKE ")
                .replaceAll("<>''", " is not null ")
                .replaceAll("<> ''", " is not null ")
                .replaceAll("!=''", " is not null ")
                .replaceAll("!= ''", " is not null ")
                .replaceAll("=''", " is null ")
                .replaceAll("= ''", " is null ");
    }
}
